import monUpload from "common/plug/Upload";
import { MonToastr as toastr } from 'mon-util'
import Util from "common/util";

/**
 * 通信聊天公共业务
 */
export default {
    data() {
        return {
            // 配置信息
            config: {},
            // 通信配置信息
            chatConfig: {},
            chatInfo: {},
            // 输入内容
            content: '',
            // websocket
            ws: null,
            // 输入框的内容
            content: "",
            // 表情包组件
            emoji: null,
            // 上传组件
            upload: null,
            // 添加链接框
            showLink: false,
            // 提示框
            showAlert: false,
            // 提示信息
            alertMsg: '',
            // 关闭提示框
            showClose: false,
            // 通话记录
            chats: [],
        }
    },
    mounted() {
        // ctrl + enter发送
        document.getElementById("text-input").addEventListener("keydown", function (e) {
            if (e.ctrlKey && e.keyCode == 13) {
                document.getElementById("send").click();
            }
        });
    },
    watch: {
        // 监听聊天列表变化
        chats(val, old) {
            this.$nextTick(() => {
                this._contentToBottom();
            });
        },
        '$route': function (val) {
            // 切换路由回聊天页面，存在聊天框则聊天框拉到最下
            if (val.name == 'chat' && this.useChat) {
                this._contentToBottom();
            }
        }
    },
    methods: {
        // websocket发送数据
        sendData(data) {
            if (this.chatInfo.transfer) {
                toastr.send('会话已转接！')
                return false;
            }
            this.ws.send(JSON.stringify(data));
        },
        // 添加链接弹窗
        showLinkDialog() {
            this.showLink = true;
        },
        // 取消添加链接
        linkCancel() {
            this.showLink = false;
        },
        // 确认添加链接
        linkSuccess(data) {
            let textarea = document.querySelector("#text-input");
            let linkCode = "[monlink:" + data.link + "=>" + data.title + ":monlink]";
            // 插入内容
            insertAtCursor(textarea, linkCode)
            this.content = textarea.value
            this.showLink = false;
        },
        // 打开提示窗
        showAlertDialog(msg) {
            this.showAlert = true;
            this.alertMsg = msg;
        },
        // 关闭提示框
        alertClose() {
            this.alertMsg = "";
            this.showAlert = false;
        },
        // 关闭会话提示
        onClose() {
            if (this.ws !== null) {
                this.showClose = true;
            }
        },
        // 关闭会话
        close() {
            this.ws.close()
            this.ws = null
            this.showClose = false
        },
        // 发送信息
        send() {
            if (this.content.trim() == "") {
                return false;
            }
            if (!this.ws) {
                this.showAlertDialog('未成功链接客服中心，请稍后再试');
                return false;
            }
            let data = {
                cmd: this.config.cmd,
                type: "send",
                dataType: 'text',
                content: this.content,
                to: this.chatConfig.group
            };
            this.sendData(data);
            this.content = "";
        },
        // 初始化聊天列表
        initList(list, tips) {
            this.chats = [];
            if (tips) {
                this.chats.push({
                    type: "tips",
                    message: false,
                    content: chatMessage.parse("tips", {
                        content: tips
                    }),
                });
            }
            list.forEach(item => {
                let content = JSON.parse(item.content)
                let className = (content.from == this.chatConfig.uid) ? "ask" : "reply";
                let sdk = chatMessage.setPath('/static/libs/monEmoji/img/')
                let date = Util.formatDate(item.create_time, 'm-d-H-i')
                let messgae = sdk.parse(content.type, content, date, className)
                this.chats.push({
                    type: className,
                    message: false,
                    content: messgae
                });
            })

        },
        // 拉到底部
        _contentToBottom() {
            let div = document.getElementById("content");
            div.scrollTop = div.scrollHeight;
        },
        // 初始化emoji
        _initEmoji() {
            let textarea = document.querySelector("#text-input");
            let that = this;
            // 加载表情包
            this.emoji = new monEmoji({
                wrapper: "#emoji",
                path: this.config.emojiSetting.path || "",
                col: 7,
                emojis: this.config.emojiSetting.emoji || null,
                callback: function (emojiCode) {
                    document.getElementById("emoji").style.display = "none";
                    // 插入内容
                    insertAtCursor(textarea, emojiCode)
                    that.content = textarea.value
                }
            });
            // 选择表情
            document.querySelector("#emoji-btn").onclick = function (e) {
                let el = document.getElementById("emoji");
                if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === "none") {
                    el.style.display = "" || "block";
                } else {
                    el.style.display = "none";
                }
            };
            document.onclick = function (e) {
                if (e.target.closest(".mEmoji-content") == null && e.target.closest("#emoji-btn") == null) {
                    if (document.getElementById("emoji")) {
                        document.getElementById("emoji").style.display = "none";
                    }
                }
            };
        },
        // 初始化上传组件
        _initUpload() {
            this.upload = new monUpload({
                elem: "#upload-btn",
                url: this.config.uploadLink,
                ext: ["jpg", "jpeg", "png", "gif"],
                maxSize: 2000,
                params: {},
                success: data => {
                    if (data.code == "1") {
                        if (!this.ws) {
                            this.showAlertDialog('未成功链接客服中心，请稍后再试');
                            return false;
                        }
                        let res = {
                            cmd: this.config.cmd,
                            type: "send",
                            dataType: 'img',
                            content: data.data.url,
                            to: this.chatConfig.group,
                            app: this.chatInfo.app || this.config.app
                        };
                        // this.ws.send(JSON.stringify(res));
                        this.sendData(res);
                    } else {
                        this.showAlertDialog('图片发送失败');
                    }
                },
                error: data => {
                    toastr.send(data.msg)
                }
            });
        },
    }
}

/**
 * 在textarea光标处插入内容
 * 
 * @params textareaDom textarea的dom对象
 * @params insertValue 插入的内容
 */
function insertAtCursor(textareaDom, insertValue) {
    if (document.selection) {
        textareaDom.focus();
        sel = document.selection.createRange();
        sel.text = insertValue;
        sel.select();
    } else if (textareaDom.selectionStart || textareaDom.selectionStart == '0') {
        let startPos = textareaDom.selectionStart;
        let endPos = textareaDom.selectionEnd;
        let restoreTop = textareaDom.scrollTop;
        textareaDom.value = textareaDom.value.substring(0, startPos) + insertValue + textareaDom.value.substring(endPos, textareaDom.value.length);
        if (restoreTop > 0) {
            textareaDom.scrollTop = restoreTop;
        }
        textareaDom.focus();
        textareaDom.selectionStart = startPos + insertValue.length;
        textareaDom.selectionEnd = startPos + insertValue.length;
    } else {
        textareaDom.value += insertValue;
        textareaDom.focus();
    }
}